package cn.crawler.app.crown.commons.websocket.monitor;

import cn.crawler.app.sys.modules.services.SysIPTablesService;
import cn.crawler.framework.util.Result;
import cn.crawler.app.crown.commons.websocket.main.monitor.BaseNettyMonitor;
import cn.crawler.app.crown.commons.websocket.main.monitor.NettyMonitor;
import com.alibaba.dubbo.config.annotation.Reference;
import io.netty.channel.ChannelHandlerContext;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;

import java.net.InetSocketAddress;

/**
 * 建立连接进行检验
 */
@IocBean
@NettyMonitor(order = -1)
public class ConnectNettyMonitor extends BaseNettyMonitor {

    @Reference
    @Inject
    private SysIPTablesService sysIPTablesService;

    @Override
    public void added(ChannelHandlerContext ctx) {
        InetSocketAddress insocket = (InetSocketAddress) ctx.channel().remoteAddress();
        String ip = insocket.getAddress().getHostAddress();
        if (!sysIPTablesService.queryAll().contains(ip)) {
            Result.breakWith(String.format("the ip %s not in ip white list.", ip));
        }
    }

    @Override
    public void removed(ChannelHandlerContext ctx) {

    }
}
